﻿package com.maomao.xpath.utils;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathUtils {

	public static DocumentBuilder generateDocumentBuilder() {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = null;
		try {
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return builder;
	}

	public static Document generateDocument(String fileName) {
		DocumentBuilder builder = generateDocumentBuilder();
		Document doc = null;
		try {
			doc = builder.parse(fileName);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	public static XPath generateXPath() {
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		return xpath;
	}

	public static NodeList queryNodelist(String filename, String exprString) {

		XPath xpath = generateXPath();
		NodeList nodes = null;
		Document doc = generateDocument(filename);
		try {
			XPathExpression expr = xpath.compile(exprString);
			Object result = expr.evaluate(doc, XPathConstants.NODESET);
			nodes = (NodeList) result;
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return nodes;
	}

}
